import 'dart:developer' as dev;

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/select_user_dao.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/select_user.dart';
import 'package:changxindianzishangwu/pages/contacts/search_userid_page.dart';
import 'package:changxindianzishangwu/pages/contacts/user_cart/user_check_page.dart';
import 'package:changxindianzishangwu/pages/message/QR_view_example.dart';
import 'package:changxindianzishangwu/pages/my/zxing_page.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/login_zxing_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class NewFriendsPage extends StatefulWidget {
  NewFriendsPage({Key key}) : super(key: key);

  @override
  _NewFriendsPageState createState() => _NewFriendsPageState();
}

class _NewFriendsPageState extends State<NewFriendsPage> {
  var packageName = "NewFriendsPage：：";
  @override
  void dispose() {
    print('二维码-----销毁 dispose');
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "新的朋友"),
      body: ListView(
        children: [
          Container(
            color: Colors.white,
            child: Column(
              children: [
                InkWell(
                  onTap: () {
                    // dev.log(packageName + "搜索聊天记录跳转");
                    Get.to(() => SearchUserIdPage());
                  },
                  child: Container(
                    color: Colors.white,
                    child: Container(
                        height: ScreenUtil().setHeight(32),
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(left: 20),
                        margin: EdgeInsets.only(
                            left: ScreenUtil().setWidth(10),
                            top: ScreenUtil().setHeight(10),
                            right: ScreenUtil().setWidth(15)),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(241, 241, 241, 1),
                            borderRadius: BorderRadius.circular(6)),
                        child: Text(
                          "手机号/用户ID",
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(153, 153, 153, 1)),
                        )),
                  ),
                ),
                InkWell(
                  onTap: () {
                    dev.log(packageName + "_zXingCode");
                    _zXingCode();
                  },
                  child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                    child: ListTile(
                      leading: Container(
                        height: ScreenUtil().setWidth(30),
                        width: ScreenUtil().setWidth(30),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6),
                          color: ZdColor.rgba(33, 144, 255, 1),
                        ),
                        child: Image.asset(
                          "images/扫一扫 (1).png",
                          height: ScreenUtil().setHeight(16),
                          width: ScreenUtil().setWidth(16),
                          fit: BoxFit.contain,
                        ),
                      ),
                      title: Container(
                        margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                        child: Text(
                          "扫一扫",
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(16),
                          ),
                        ),
                      ),
                      subtitle: Text(
                        "扫描二维码名片",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(12),
                            color: Color.fromRGBO(153, 153, 153, 1)),
                      ),
                      trailing: Icon(Icons.keyboard_arrow_right),
                    ),
                  ),
                ),
                // Divider(
                //   height: 1,
                //   indent: ScreenUtil().setWidth(30),
                //   color: Color.fromRGBO(248, 248, 248, 1),
                //   thickness: ScreenUtil().setHeight(1),
                //   endIndent: ScreenUtil().setWidth(30),
                // ),
                // // todo 隐藏
                // InkWell(
                //   onTap: () {
                //     dev.log(packageName + "新的朋友");
                //
                //     Get.to(NewTestPage());
                //   },
                //   child: Container(
                //     child: ListTile(
                //       leading: Container(
                //         height: ScreenUtil().setWidth(30),
                //         width: ScreenUtil().setWidth(30),
                //         alignment: Alignment.center,
                //         decoration: BoxDecoration(
                //           borderRadius: BorderRadius.circular(6),
                //           color: ZdColor.rgba(0, 220, 169, 1),
                //         ),
                //         child: Image.asset(
                //           "images/微信 (3).png",
                //           height: ScreenUtil().setHeight(16),
                //           width: ScreenUtil().setWidth(16),
                //           fit: BoxFit.contain,
                //         ),
                //       ),
                //       title: Container(
                //         margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                //         child: Text(
                //           "邀请微信好友",
                //           style: TextStyle(
                //             fontSize: ScreenUtil().setSp(16),
                //           ),
                //         ),
                //       ),
                //       subtitle: Text(
                //         "邀请您的微信好友加入",
                //         style: TextStyle(
                //             fontSize: ScreenUtil().setSp(12),
                //             color: Color.fromRGBO(153, 153, 153, 1)),
                //       ),
                //       trailing: Icon(Icons.keyboard_arrow_right),
                //     ),
                //   ),
                // ),
              ],
            ),
          ),
          //  todo 隐藏
          InkWell(
            onTap: () {
              dev.log(packageName + "新的朋友");
            },
            child: Container(
              color: Colors.white,
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(13)),
              child: ListTile(
                leading: Container(
                  height: ScreenUtil().setWidth(30),
                  width: ScreenUtil().setWidth(30),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(6),
                    color: ZdColor.rgba(242, 181, 37, 1),
                  ),
                  child: Image.asset(
                    "images/二维码.png",
                    height: ScreenUtil().setHeight(16),
                    width: ScreenUtil().setWidth(16),
                    fit: BoxFit.contain,
                  ),
                ),
                title: Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                  child: Text(
                    "我的二维码",
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(16),
                    ),
                  ),
                ),
                subtitle: Text(
                  getUserInfo().account,
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(12),
                      color: Color.fromRGBO(153, 153, 153, 1)),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
                onTap: () {
                  Get.to(ZxingPage());
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///--------------------------------扫描二维码 start
  _zXingCode() async {
    var value = await Get.to(QRViewExample());
    if (value == null) return;

    if (value.contains("user")) {
      String key = "qrCodeKey=";
      int index = value.indexOf(key);
      String _userMsg = value.substring(index + key.length, value.length);
      EasyLoading.show(status: "查询中...");
      getServiceData(_userMsg);
    } else if (value.contains("webLogin")) {
      EasyLoading.show();
      _qrLogin(value);
    } else {
      toast("扫描结果:$value");
    }
  }

  SelectUser user;

  getServiceData(userId) async {
    user = await SelectUserDao.getUserInfo(userId);
    if (user.data.length == 0) {
      toast("暂未查找到该好友");
      EasyLoading.dismiss();
    } else {
      _findUserFriends();
    }
  }

  _findUserFriends() async {
    print('二维码  _findUserFriends');
    try {
      V2TimValueCallback<List<V2TimFriendInfoResult>> v2TimFriendInfoResult =
          await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
              .getFriendsInfo(userIDList: [user.data[0].userId.toString()]);
      EasyLoading.dismiss();

      if (v2TimFriendInfoResult.data.length == 0) {
        toast("暂未查找到该好友");
      } else {
        print("二维码 跳转页面：UserCheckPage");

        Get.to(() => UserCheckPage(
              userId: user.data[0].userId.toString(),
              ziyuId: user.data[0].account.toString(),
              userEntity: v2TimFriendInfoResult.data[0].friendInfo.userProfile,
              type: 2,
            ));
      }
    } catch (e) {
      EasyLoading.dismiss();
      toast("暂未查找到该好友");
      print(e);
    }
  }

  void _qrLogin(value) async {
    String key = "qrCodeKey=";
    int index = value.indexOf(key);
    String _userMsg = value.substring(index + key.length, value.length);
    BaseModel _model = await LoginInitDao.qrLogin(_userMsg, 1);
    if (_model.resultCode == 1) {
      Future.delayed(Duration(milliseconds: 500), () {
        EasyLoading.dismiss();
        Get.to(LoginZxingDialog(_userMsg));
      });
    } else {
      EasyLoading.dismiss();
      toast("登录失败：${_model.resultMsg}");
    }
  }

  ///--------------------------------扫描二维码 end
}
